
Request.implement({
    failure: function() {
        if (this.status == 401) {
            alert("未登录");
        } else {
            if (this.status == 599) {
                alert(JSON.decode(this.getHeader("warning")));
            }
            this.onFailure();
        }
    }
});

Form.Validator.addAllThese([
    ['validate-positiveInteger', {
        errorMsg: '请输入一个大于或等于0的的整数，例如 1, 10, 11',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return (/^([1-9]\d*|0)$/).test(element.get('value'));
            }

        }
    }],
    ['validate-positiveGreaterThanZero', {
        errorMsg: '请输入一个大于0的整数。例如： 1,99。',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return  (/^(?:0$0(?=\d*\.)|[1-9])\d*(\.\d+)?$/).test(element.get('value'));
            }
        }
    }],

    ['validate-positiveNumeric', {
        errorMsg: '请输入一个大于或等于0的数字。例如： 1, 1.1。',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return  (/^(?:0$0(?=\d*\.)|[1-9]|0)\d*(\.\d+)?$/).test(element.get('value'));
            }
        }
    }],

    ['validate-NumGreaterThanZero', {
        errorMsg: '请输入一个大于0的数字。例如： 1, 1.1。',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return  (/^(?:\d*\.\d+|[1-9]\d*)$/).test(element.get('value'));
            }
        }
    }],

    ['validate-mobile', {
        errorMsg: '手机号应该为11位数字',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return (element.get('value').length  == 11) && (/^\d+$/).test(element.get('value'));
            }
        }
    }],

    ['validate-phone', {
        errorMsg: '请填写正确的电话号码，区号和电话号码之间请用-分隔',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return (/^(0\d{2,3})-(\d{7,8})(-(\d{2,}))?$/).test(element.get('value'));
            }
        }
    }],
    ['validate-qq', {
        errorMsg: '请填写正确的QQ号码',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return (/^[1-9]\d{4,}$/).test(element.get('value'));
            }
        }
    }],

    ['validate-zipcode', {
        errorMsg: '请填写正确的邮编，由六位数字组成',
        test: function(element){
            if (element.get('value').trim() == '')
            {
                return true;
            } else {
                return (/^\d{6}(?!\d)$/).test(element.get('value'));
            }
        }
    }],
    ['validate-color', {
        errorMsg: '请选择相应的颜色值',
        test: function(field){
                if(field.get('value').trim() == ''){
                   return false;
                }else{
                   return true;
                }
        }
   }],
   ['validate-file', {
        errorMsg: '请选择上传的文件',
        test: function(field){
                if(field.get('value').length  == 0){
                    return false;
                }else{
                    return true;
                }
            }
      }]


]);

function searchInfo(obj, url) {
    new Request.HTML({
        url: './'+url,
        onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
            $('facebox').getElement('.returnElementClass').innerHTML = '';
            $('facebox').getElement('.returnElementClass').innerHTML = responseHTML;
            if($('facebox').getElement('input')) {
                $('facebox').getElement('input[name=selectAllBtn]').disabled = false;
            } else {
                 $('facebox').getElement('input[name=selectAllBtn]').disabled = true;
            }

            if (typeof excludePIds != "undefined") { //不包含的商品ID
                $('facebox').getElements('input[type=checkbox]').each(function(item) {
                    excludePIds.each(function (id){
                        if(item.get('value') == id) {
                            item.set('disabled', true);
                            return;
                        }
                    });
                });
            }
        }
    }).get($(obj.form));
}

function copyInfo(type, obj, resultId, checkBoxName) {
    if(type == 1) {
        var returnElements = $('facebox').getElement('.returnElementClass').getElements("input:checked").getParent();//新选择的
        var existsElements = $(resultId).getElements('input[name^='+checkBoxName+']');//获得已存在的

        /*如果是已存在的就不inject*/
        if(existsElements.length) {
            var exists = new Array();
            existsElements.each(function(item, index){
                exists.include(item.value.toInt());
            });

            returnElements.each(function(item, index){
                if(!exists.contains(item.getElement('input[name^='+checkBoxName+']').value.toInt())) {
                    item.checked = true;
                    item.inject($(resultId),'top')
                }
            });
        } else {
            returnElements.inject($(resultId),'top');
            $(resultId).getElements('input[name^='+checkBoxName+']').each(function(el){
                el.checked = true;
            })
        }
    }
    closeFacebox();
}

function closeFacebox(){
    window.fb.close();
}

function selectAll(obj, checkBoxName) {
    var inputs = $('facebox').getElements('input[name^='+checkBoxName+']')
    if (obj.value == '选择全部') {
        inputs.each(function(el) {
            el.checked = true;
        });
        obj.value = '取消全选';
    } else {
        inputs.each(function(el) {
            el.checked = false;
        });
        obj.value = '选择全部';
    }
}



window.addEvent("domready", function() {
    if (typeof CalendarEightysix == 'undefined') {
        return;
    } else {
        CalendarEightysix.instances = [];
        CalendarEightysix.implement((function() {
            var oldInitMethod = CalendarEightysix.prototype.initialize;
            var oldShowMethod = CalendarEightysix.prototype.show;
            return {
                show: function() {
                    var self = this;
                    CalendarEightysix.instances.each(function(ins) {
                        if (ins != self) {ins.hide();}
                    });
                    oldShowMethod.apply(this);
                },
                initialize: function() {
                    oldInitMethod.apply(this, arguments);
                    CalendarEightysix.instances.push(this);
                }
            }
        })());
    }
});

var CrossSiteRequest = new Class({
    options: {
        method: 'get'
    },
    Implements: [Events, Options],
    initialize: function(url) {
        this.url = url;
        this.state = 0;
    },
    createFrame: function() {
        try {
            var self = this;
            var s = this.frame = document.createElement('iframe');
            s.onload = s.onreadystatechange = function() {
                if (this.readyState && this.readyState == "loading") {
                    return;
                }
                self.loaded();
            };
            this.frame.style.display = "none";
        } catch(ex) {}
    },
    loaded: function() {
        if (this.state == 0) {
            this.frame.contentWindow.location.href = "/blank.php";
            this.state = 1;
        } else {
            var name = decodeURIComponent(this.frame.contentWindow.name).replace(/\+/g, ' ');
            this.fireEvent('onComplete', JSON.decode(name));
            try {
                document.body.removeChild(this.frame);
            } catch (ex) {}
        }
    },
    request: function() {
        this.createFrame();
        var uri = new URI(this.url).setData({windowName: true}, true);
        this.frame.src = uri.toString();
        document.body.appendChild(this.frame);
    }
});


var CrossSiteFromRequest = new Class({
    options: {
        method: 'get'
    },
    Implements: [Events, Options],
    initialize: function(form, options) {
        this.options = this.setOptions(options);
        this.frame = new IFrame({

        }).inject(document.body).hide();
        form.set('target', this.frame.name);
        this.state = 0;
    },
    loaded: function(data) {

    }
});



/**
验证码类

new Captcha(input);
*/

var Captcha = new Class({
    Binds:["docMouseDown", "focus", "changeCaptchaImg", "blur"],
    initialize: function(textbox, verification) {
        this.el = $(textbox);
        this.verification = $(verification);
        if (!this.verification) {
            var verifHTML = '<div class="verification" style="display: none; zIndex:9999;">' +
                            '<span class="left"></span>' +
                            '<span class="content"><img width="120" height="70" id="captchaImg"/><a href="javascript:void 0;" id="newCaptcha" style="cursor: pointer;">看不清,换一张</a></span>' +
                            '<span class="right"></span>' +
                            '</div>';
            this.verification = Elements.from(verifHTML).inject(document.body)[0];
        }
        this.el.addEvent('focus', this.focus);
        this.el.addEvent('click', this.focus);
        this.first = true;

        var a = this.verification.getElement("a");
        a.addEvent("click", this.changeCaptchaImg);
        this.verification.getElements("*").set("unselectable", "on"); // 兼容IE6
        this.pollHand = false;
        Captcha.addCaptcha(this);
    },
    polling: function() {
        if (!this.verification.isDisplayed()) this.stopPoll();
        this.verification.show().position({
            relativeTo: this.el,
            position: {x: "right", y: "top"},
            offset: {y: -40}
        });
    },
    stopPoll: function() {
        $clear(this.pollHand);
    },
    startPoll: function() {
        this.pollHand = this.polling.periodical(100, this);
    },
    focus: function() {
        if (this.verification.isDisplayed()) {
            return;
        }
        var verif = this.verification;
        //alert(this.el.getPosition().x);
        verif.position({
            relativeTo: this.el,
            position: {x: "right", y: "top"},
            offset: {y: -40}
        }).show();

        if (this.first) {
            verif.getElement("a").fireEvent("click");
            this.first = false;
        }
        this.startPoll();
        $(document).addEvent("mousedown", this.docMouseDown);
        this.el.addEvent("blur", this.blur);
    },
    blur: function() {
        this.stopPoll();
        this.verification.hide();
        document.removeEvent("mousedown", this.docMouseDown);
    },
    docMouseDown: function(e) {
        var target = $(e.target);
        if (target != this.el && (target != this.verification && ! this.verification.hasChild(target)) &&
            (!target.hasClass("overTxtLabel") || (target.hasClass("overTxtLabel") && target.get("for") != this.el.get("id")))) {
            this.blur();
        } else {
            e.stop();
        }
    },
    changeCaptchaImg: function(e) {
        var verif = this.verification;
        verif.getElement("img").set("src", Captcha.captchaService + '&' + Math.random());
    }
});

Captcha.extend({
    arr: [],
    addCaptcha: function(captcha) {
        this.arr.push(captcha);
    },
    hideAll: function() {
        this.arr.each(function(c){
            c.blur();
        });
    }
});

Captcha.captchaService = '';